
import { doLogin, doLogout } from 'services/authorization';
import { isInFirstUseArea } from 'services/access';
import { routerTool } from 'utils';
import { message } from 'antd';

/* global window */

export default {
  namespace: 'user',

  state: {

    // 当前用户所处学校
    school: {},

    // 当前用户所处社团
    organization: {},

    // 当前用户拥有的社团
    organizations: [],

    // 当前用户的登录令牌
    token: null,

    // 当前用户的个人信息
    userInfo: {
      ID: null,
    },

    // 当前用户所拥有的权限
    permissions: {
      // 当前用户拥有权限的路由
      routes: [],

      // 当前用户可见的功能
      visit: [],
    },
  },

  subscription: {
    setup ({ dispatch, history }) {
      // 订阅
    },
  },

  reducers: {
    setSchool (state, { payload }) {
      return {
        ...state,
        ...{
          school: payload,
        },
      };
    },

    updateToken (state, { payload }) {
      return {
        ...state,
        ...{
          token: payload,
        },
      };
    },

    updateState (state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    clearToken (state) {
      return {
        ...state,
        ...{
          token: null,
        },
      };
    },
  },

  effects: {

    // 登录
    *login ({ payload }, { put, call, select }) {
      const { locationQuery } = yield select(_ => _.app);
      const { success, results, message: msg } = yield call(doLogin, payload);
      const { Token, User } = results;

      const {
        School,
        CurrentOrganization,
        Departments,
        Organizations,
        ...userInfo
      } = (User || {});

      if (success) {
        const { from } = locationQuery;
        const hasOrganization = (!!CurrentOrganization.ID || (Organizations && (Organizations.length || 0) > 0));
        yield put({
          type: 'updateState',
          payload: {
            token: Token,
            school: School,
            organization: CurrentOrganization,
            organizations: Organizations,
            userInfo,
          },
        });
        // console.log('登录成功');
        if (!hasOrganization) {
          // 不存在组织时
          console.log('不存在组织，跳转到提醒页面');
          yield put(routerTool.redirectTo('OrganizationAlert'));
        } else if (from && from !== routerTool.getPathByName('Login')) {
          yield put(routerTool.redirectTo({
            pathname: from,
          }));
        } else {
          yield put(routerTool.redirectTo("Home"));
        }
      } else {
        message.error(msg);
      }
    },

    // 注销
    *logout (_, { put, call }) {
      const data = yield call(doLogout);
      if (data.success) {
        // yield put({ type: 'app/query' });
        yield put({ type: 'clearToken' });
        yield put(routerTool.redirectTo('Login'));
      } else {
        throw (data);
      }
    },

    // 检查当前用户的组织是否存在, 若不存在跳转到 OrganizationAlert 页面
    *checkOrganization ({ payload = {} }, { put, call, select }) {
      let hasOrganization = false;
      if (Object.prototype.hasOwnProperty.call(payload, 'hasOrganization')) {
        hasOrganization = payload.hasOrganization;
      } else {
        const { organization, organizations } = yield select(_ => _.user);
        hasOrganization = (!!organization.ID || (organizations && (organizations.length || 0) > 0));
      }
      const { locationPathname } = yield select(_ => _.app);
      const inFirstUseArea = yield call(isInFirstUseArea, locationPathname);
      if (!hasOrganization && !inFirstUseArea) {
        yield put(routerTool.redirectTo({
          name: 'OrganizationAlert',
        }));
      }
    },

    // 清除登录信息
    *clearLoginInfo (_, { put, call }) {
      yield put({ type: 'clearToken' });
      yield put({
        type: 'updateState',
        payload: {
          // 当前用户所处社团
          organization: {},

          // 当前用户的登录令牌
          token: null,

          // 当前用户的个人信息
          userInfo: {
            ID: null,
          },

          // 当前用户所拥有的权限
          permissions: {
            // 当前用户拥有权限的路由
            routes: [],

            // 当前用户可见的功能
            visit: [],
          },
        },
      });
    },

  },
};
